package esi.t2no1.web.jobs;

import java.util.Arrays;
import java.util.Collections;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value = "/quartz")
public class QuartzController {
	
	private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory
			.getLogger(QuartzController.class);
	
	private Scheduler factory;

	public QuartzController() {
		// Nothing
	}

	@RequestMapping(method = RequestMethod.GET)
	public String propagateMeterData(Model model) {
		Scheduler scheduler = getFactory();
	    try {
			model.addAttribute("jobs", scheduler.getJobNames("DEFAULT"));
		} catch (SchedulerException e) {
			model.addAttribute("jobs", Collections.EMPTY_SET);
		}

		return "jobs/view";
	}
	
	@RequestMapping(value = "{jobName}", method = RequestMethod.GET)
	public String runJob(@PathVariable String jobName) {
		if (jobName.isEmpty()) {
			LOG.warn("Empty job name given");
			return "redirect:/quartz";
		}
		try {
			if (!Arrays.asList(getFactory().getJobNames("DEFAULT")).contains(jobName)) {
				LOG.warn("Scheduler does not contain job: " + jobName);
				return "redirect:/quartz";
			}
			getFactory().triggerJob(jobName, "DEFAULT");
		} catch (SchedulerException e) {
			LOG.error(e.toString());
			return "redirect:/quartz";
		}
		
		return "redirect:/quartz";
	}

	public Scheduler getFactory() {
		return factory;
	}

	@Autowired
	public void setFactory(Scheduler factory) {
		this.factory = factory;
	}
}
